package com.oanda.blackberry.util;

import net.rim.device.api.util.MathUtilities;

public class StringUtils {
    public static String formatDouble(double f, int len) {
        String s = Double.toString(f);
        int i = s.indexOf(".");

        String temp = "";
        if (i < s.length() - 1) {
            temp = s.substring(i + 1, s.length());
        }
        if (temp.length() == len) {
            return s;
        }
        if ((len < temp.length()) && (len > -1)) {
            return s.substring(0, s.length() - Math.abs(temp.length() - len));
        }

        for (int j = 0; j < len - temp.length(); j++) {
            s = s + "0";
        }
        return s;
    }

    public static String formatCurrency(double input) {
        char delimiter = ',';
        String negative = "";

        if (input < 0.0D) {
            input = Math.abs(input);
            negative = "-";
        }

        StringBuffer output = new StringBuffer();
        int dollars = (int) input;

        String dol = Integer.toString(dollars);
        int i = 0;
        char[] c = dol.toCharArray();

        for (int j = c.length - 1; j >= 0; j--) {
            char d = c[j];
            output.append(d);
            i++;
            if ((i % 3 == 0) && (dol.length() > 3) && (j != 0)) {
                i = 0;
                output.append(delimiter);
            }
        }
        output.reverse();

        double res = input - dollars;
        int centsI = (int) (res * 100.001D);

        if (centsI == 0) {
            return negative + output.toString() + ".00";
        }

        output.append('.');
        StringBuffer cents = new StringBuffer(String.valueOf(centsI));

        while (cents.length() < 2) {
            cents.insert(0, "0");
        }

        if (cents.length() > 2) {
            cents.toString().substring(0, 2);
        }

        output.append(cents);
        return negative + output.toString();
    }

    public static double columnRound(double arg, int places) {
        double tmp = arg * MathUtilities.pow(10.0D, places);
        double tmp1 = Math.floor(tmp + 0.5D);
        double tmp2 = tmp1 / MathUtilities.pow(10.0D, places);
        return tmp2;
    }
}
